import { Component, EventEmitter, Input, OnInit, Output, TemplateRef } from '@angular/core';
import { ConfigModule } from '../../config.module';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Router } from '@angular/router';
import { environment } from '../../../environments/environment';
import { WebStorageService } from '../../services/webStorage.service';

const getBase64 = (file: File): Promise<string | ArrayBuffer | null> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

@Component({
    selector: 'app-image-upload-file',
    templateUrl: './image-upload-file.component.html',
    styleUrls: ['./image-upload-file.component.scss']
})
export class ImageUploadFileComponent implements OnInit {
    @Input() fileList: NzUploadFile[] = []; //页面显示的图片数组
    @Output() fileListChange: EventEmitter<any> = new EventEmitter<any>();
    uploading = false; //是否在上传进程中
    @Input() fileType: string; //允许的文件类型
    @Input() uploadPath = environment.baseUrl + 'base/public/success'; //上传文件路径
    @Input() acceptListLength: number=1; //允许上传的文件个数
    token: string;
    @Input() formName = "avatarfile";
    previewImage: string | undefined = '';
    previewVisible = false;
    @Input()
    avatarShowTemplate: TemplateRef<any> = null;

    constructor(private nzMessage: NzMessageService,
                private router: Router,
                public config: ConfigModule,
                private webStorageService: WebStorageService
    ) {}

    ngOnInit() {
        this.token = this.webStorageService.getToken();
    }

    beforeUpload = (file: NzUploadFile): boolean => {
        this.fileList = this.fileList.concat(file);
        this.handlePreview(file).then(r => false);
        return false;
    }

    handleUpload(): void {
        this.fileListChange.emit(this.fileList);
    }

    handlePreview = async(file: NzUploadFile): Promise<void> => {
        if (!file.url && !file.preview) {
            // tslint:disable-next-line:no-non-null-assertion
            file.preview = await getBase64(file.originFileObj!);
        }
        this.previewImage = file.url || file.preview;
        this.previewVisible = true;
    }
}
